package com.lxp.eduService.service.impl;

import com.alibaba.excel.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lxp.eduService.client.VodClient;
import com.lxp.eduService.domain.EduChapter;
import com.lxp.eduService.domain.EduCourse;
import com.lxp.eduService.domain.EduCourseDescription;
import com.lxp.eduService.domain.EduVideo;
import com.lxp.eduService.domain.vo.CourseInfo;
import com.lxp.eduService.domain.vo.front.CourseFrontInfoVo;
import com.lxp.eduService.domain.vo.publish.CoursePublishVo;
import com.lxp.eduService.domain.vo.queryVo.CourseFrontVo;
import com.lxp.eduService.mapper.EduCourseMapper;
import com.lxp.eduService.service.EduCourseDescriptionService;
import com.lxp.eduService.service.EduCourseService;
import com.lxp.servicebase.exception.MyException;
import com.lxp.utils.R;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author lxp
 * @since 2021-11-20
 */
@Service
public class EduCourseServiceImpl extends ServiceImpl<EduCourseMapper, EduCourse> implements EduCourseService {

    @Autowired
    private EduCourseDescriptionService descriptionService;
    //注入小节服务实现类
    @Autowired
    private EduVideoServiceImpl eduVideoService;
    //注入章节服务实现类
    @Autowired
    private EduChapterServiceImpl eduChapterService;
    @Autowired
    private VodClient client;


    //添加课程
    @Override
    public String addCourse(CourseInfo courseInfo) {
        //将数据封装到 EduCourse去
        EduCourse eduCourse = new EduCourse();
        BeanUtils.copyProperties(courseInfo, eduCourse);

        //将EduCourse存到数据库去
        int insert = baseMapper.insert(eduCourse);
        //判断是否存储成功
        if (insert == 0) {
            //存失败了
            throw new MyException(20001, "添加课程失败");
        }


        //将课程简介存到简介表里面去
        EduCourseDescription eduCourseDescription = new EduCourseDescription();
        //确保课程简介的id和课程的id相同
        eduCourseDescription.setId(eduCourse.getId());
        //保存简介信息
        eduCourseDescription.setDescription(courseInfo.getDescription());
        descriptionService.save(eduCourseDescription);

        String courseId = eduCourse.getId();
        return courseId;
    }

    //根据id 查询出CourseInfo
    @Override
    public CourseInfo getCourseInfo(String courseId) {
        CourseInfo info = new CourseInfo();
        //根据id 查询出课程
        EduCourse eduCourse = baseMapper.selectById(courseId);
        //根据id 查询出简介
        EduCourseDescription description = descriptionService.getById(courseId);
        //封装信息到CourseInfo
        BeanUtils.copyProperties(eduCourse, info);
        BeanUtils.copyProperties(description, info);
        return info;
    }

    //修改课程
    @Override
    public void updateCourse(CourseInfo courseInfo) {
        //将courseInfo 转为 EduCourse
        EduCourse eduCourse = new EduCourse();
        BeanUtils.copyProperties(courseInfo, eduCourse);
        //修改数据
        baseMapper.updateById(eduCourse);
        //将简介存到EduCourseDescription
        EduCourseDescription eduCourseDescription = new EduCourseDescription();
        BeanUtils.copyProperties(courseInfo, eduCourseDescription);
        //修改数据
        descriptionService.updateById(eduCourseDescription);
    }

    //最终发布课程
    @Override
    public CoursePublishVo publishCourse(String courseId) {
        CoursePublishVo coursePublishVo = baseMapper.publishCourse(courseId);

        return coursePublishVo;
    }

    //根据课程id 删除课程
    @Transactional
    @Override
    public void deleteByCourseId(String courseId) {
        //删除小节中的视频
        //查询出符合条件中小节的视频id
        List<EduVideo> videos = eduVideoService.list
                (new QueryWrapper<EduVideo>()
                        .eq("course_id", courseId)
                        .select("video_source_id"));
        //根据视频id删除阿里云视频
        for (EduVideo video : videos) {//取出id
            String videoSourceId = video.getVideoSourceId();
            //调用服务删除视频
            R r = client.removeAlyVideo(videoSourceId);
            //判断服务是否可调用
            if (r.getCode() == 20001) {
                throw new MyException(20001, "网络连接超时");
            }
        }
        //根据课程id 删除小节
        eduVideoService.remove(new QueryWrapper<EduVideo>().eq("course_id", courseId));
        //根据课程id 删除章节
        eduChapterService.remove(new QueryWrapper<EduChapter>().eq("course_id", courseId));
        //根据课程id 删除描述
        descriptionService.removeById(courseId);
        //根据课程id 删除课程
        baseMapper.deleteById(courseId);

    }

    @Override
    public Map<String, Object> getCourseListFront(Page<EduCourse> pageParam, CourseFrontVo courseQuery) {
        QueryWrapper<EduCourse> queryWrapper =new QueryWrapper<>();

        //拼接查询条件
        if (!StringUtils.isEmpty(courseQuery.getSubjectParentId())) {
            queryWrapper.eq("subject_parent_id", courseQuery.getSubjectParentId());
        }

        if (!StringUtils.isEmpty(courseQuery.getSubjectId())) {
            queryWrapper.eq("subject_id", courseQuery.getSubjectId());
        }


        //搜索名称
        if (!StringUtils.isEmpty(courseQuery.getSelectCourseName())) {
            queryWrapper.like("title", courseQuery.getSelectCourseName());
        }

        if (!StringUtils.isEmpty(courseQuery.getBuyCountSort())) {
            queryWrapper.orderByDesc("buy_count");
        }

        if (!StringUtils.isEmpty(courseQuery.getGmtCreateSort())) {
            queryWrapper.orderByDesc("gmt_create");
        }

        if (!StringUtils.isEmpty(courseQuery.getPriceSort())) {
            queryWrapper.orderByDesc("price");
        }

        baseMapper.selectPage(pageParam,queryWrapper);
        List<EduCourse> records = pageParam.getRecords();
        long current = pageParam.getCurrent();
        long pages = pageParam.getPages();
        long size = pageParam.getSize();
        long total = pageParam.getTotal();
        boolean hasNext = pageParam.hasNext();
        boolean hasPrevious = pageParam.hasPrevious();

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("items", records);
        map.put("current", current);
        map.put("pages", pages);
        map.put("size", size);
        map.put("total", total);
        map.put("hasNext", hasNext);
        map.put("hasPrevious", hasPrevious);

        return map;
    }

    @Override
    public CourseFrontInfoVo getCourseFrontInfo(String courseId) {
        CourseFrontInfoVo courseFrontInfo=baseMapper.getCourseFrontInfo(courseId);
        return courseFrontInfo;
    }

    //搜索框输入关键字搜索课程
    @Override
    public Page<EduCourse> selectByName(String courseName, long current, long limit) {
        Page<EduCourse> page =new Page<>(current,limit);
        baseMapper.selectPage(page,new QueryWrapper<EduCourse>()
                .like("title",courseName));
        return page;
    }
}
